package cn.tac.test.servlet.cheapter2;

import cn.tac.test.servlet.cheapter2.Constant;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : tac
 * @since : 09/09/2017
 */
public abstract class ServletFactory {
    private static final Map<String, Servlet> servlets = new HashMap<>();

    public static Servlet create(String name) {
        if (servlets.containsKey(name)) {
            return servlets.get(name);
        }

        Servlet servlet = loadServlet(name);
        if (servlet != null) {
            try {
                servlet.init(servlet.getServletConfig());
                servlets.put(name, servlet);
                return servlet;
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }

        throw new RuntimeException("load servlet error");
    }

    private static Servlet loadServlet(String name) {
        URL[] urls = new URL[1];
        try {
            urls[0] = new URL("file://" + Constant.SERVLET_PATH + File.separator + name + ".class");
            URLClassLoader loader = new URLClassLoader(urls);
            return (Servlet) loader.loadClass("cn.tac.test.servlet.cheapter2.servlet.HelloServlet").newInstance();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

}
